<?php

namespace App\Exception\Handler;

use App\Exception\ApiException;
use App\Service\BaseService;
use Hyperf\ExceptionHandler\ExceptionHandler;
use Hyperf\HttpMessage\Stream\SwooleStream;
use Psr\Http\Message\ResponseInterface;
use Throwable;

class ApiExceptionHandler extends ExceptionHandler
{

    public function handle(Throwable $throwable, ResponseInterface $response)
    {
        if ($throwable instanceof ApiException) {
            // 格式化输出
            $result = [
                'ret' => -1,
                'result' => intval($throwable->getCode()),
                'res_info' => $throwable->getMessage(),
            ];

            // 阻止异常冒泡
            $this->stopPropagation();
            return $response->withHeader("Content-Type", "application/json")
                ->withStatus(200)
                ->withBody(new SwooleStream(json_encode($result, JSON_UNESCAPED_UNICODE)));
        }

        // 交给下一个异常处理器
        return $response;
    }

    public function isValid(Throwable $throwable): bool
    {
        return true;
    }
}